package com.surfilter.geet;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {

    @SuppressWarnings("unused")
    private static Logger log = Logger.getLogger(HttpUtil.class);

    public static String get(String path) {
        String flag = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            byte[] bytes = HttpUtil.readInputStream(inStream);
            inStream.close();
            flag = new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private static byte[] readInputStream(InputStream inStream) {
        byte[] bytes = null;
        ByteArrayOutputStream outStream = null;
        try {
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            bytes = outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (Exception ignored) {
            }
        }
        return bytes;
    }

    public static byte[] getRomoteUrl(String romote_url) {
        byte[] btImg = null;
        try {
            URL url = new URL(romote_url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            btImg = HttpUtil.readInputStream(inStream);
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return btImg;
    }

    public static String httpRequest(String StrUrl, Map<String, String> params, Map<String, String> cookies) {
        if (StringUtils.isBlank(StrUrl)) {
            return null;
        }
        if (cookies == null || cookies.size() == 0) {
            return null;
        }

        if (params != null && params.size() != 0) {
            String param = httpBuildParams(params);
            StrUrl = StrUrl + "?" + param;
        }
        String cookie = HttpUtil.getCookie(cookies);
        try {
            URL url = new URL(StrUrl); // 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Cookie", cookie);
            connection.connect();
            Thread.sleep(3000);
            int code = connection.getResponseCode();
            if (code == 500 || code == 504) {
                return null;
            }
            InputStream in = connection.getInputStream();
            if (in == null) {
                return null;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // 读取响应
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            in.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public static String getSinaHtml(String url, Map<String, String> params, Map<String, String> cookies) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        if (cookies == null || cookies.size() == 0) {
            return null;
        }
        if (params != null && params.size() != 0) {
            String param = httpBuildParams(params);
            url = url + "?" + param;
        }
        try {
            Connection con = Jsoup.connect(url);
            Thread.sleep(3000);
            con.validateTLSCertificates(false);
            con.timeout(20000);
            con.cookies(cookies);
            con.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            con.header("Accept-Encoding", "gzip, deflate, sdch");
            con.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
            con.header("Cache-Control", "no-cache");
            con.header("Connection", "keep-alive");
            con.header("Pragma", "no-cache");
            con.header("Upgrade-Insecure-Requests", "1");
            con.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36");

            Document doc = con.get();
            if (doc == null) {
                return null;
            }
            return doc.html();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 参数编码
     *
     * @return
     */
    public static String httpBuildParams(Map<String, String> params) {
        String ret = "";
        String k, v;
        for (String s : params.keySet()) {
            k = s;
            v = params.get(k);
            try {
                ret += URLEncoder.encode(k, "utf8") + "=" + URLEncoder.encode(v, "utf8");
            } catch (Exception ignored) {
            }
            if (StringUtils.isNotBlank(ret)) {
                ret += "&";
            }

        }
        return ret.substring(0, ret.length() - 1);
    }

    /**
     * 获取 cookie
     *
     * @return
     */
    public static String getCookie(Map<String, String> cookies) {
        String ret = "";
        String k, v;
        Iterator<String> iterator = cookies.keySet().iterator();
        while (iterator.hasNext()) {
            k = iterator.next();
            v = cookies.get(k);
            try {
                ret += k.trim() + "=" + v.trim();
            } catch (Exception e) {
            }
            if (StringUtils.isNotBlank(ret)) {
                ret += ";";
            }
        }
        return ret.substring(0, ret.length() - 1);
    }

    public static void main(String[] args) {

        Map<String, String> par = new HashMap();
        par.put("type", "enterprise");
        par.put("source", "");
        par.put("isGlobal", "Y");
        par.put("key", "阿里巴巴");

        Map<String, String> cookies = new HashMap();
        cookies.put("tencentSig", "5242560512");
        cookies.put("pgv_pvi", "8118023168");
        cookies.put("aliyungf_tc", "AQAAALhyEFQuqw4A8jpsO0507+tksxV1");
        cookies.put("sid", "s%3A-yk05fvBpV2r60diIGwPvtGgUZsywegc.FALH03hEzCdjlqBmp7gMY5JnPpMAnPq5BTcCIyI2XAw");
        cookies.put("hide-download-panel", "1");
        cookies.put("_qddamta_800809556", "3-0");
        cookies.put("responseTimeline", "110");
        cookies.put("Hm_lvt_52d64b8d3f6d42a2e416d59635df3f71", "1482126548,1482145839,1482219577,1482222648");
        cookies.put("Hm_lpvt_52d64b8d3f6d42a2e416d59635df3f71", "1482224621");
        cookies.put("_zg",
                "%7B%22uuid%22%3A%20%2215915a05d3f31e-0084b62c458fe6-3764460e-13c680-15915a05d4015%22%2C%22sid%22%3A%201482222648.67%2C%22updated%22%3A%201482224621.596%2C%22info%22%3A%201482126548296%2C%22cuid%22%3A%20%22b28fbca7-c624-4788-85c6-475b0b370dc8%22%7D");
        cookies.put("_qddaz", "QD.esldji.x205iu.iwvnw6gb");
        cookies.put("_qdda", "3-1.2fy7d");
        cookies.put("_qddab", "3-bkjhq5.iwx93fno");

        String ss = HttpUtil.getSinaHtml("http://www.qixin.com/search", par, cookies);

        File file = new File("D:/2.txt");
        PrintWriter prit;

        try {
            file.createNewFile();
            prit = new PrintWriter(file);
            prit.write(ss);
            prit.close();
            prit.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
